package com.gensdai.leliang.activity;

import android.content.Context;
import android.content.Intent;
import android.graphics.Rect;
import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.widget.RelativeLayout;

import com.alibaba.android.vlayout.DelegateAdapter;
import com.alibaba.android.vlayout.VirtualLayoutManager;
import com.alibaba.android.vlayout.layout.LinearLayoutHelper;
import com.gensdai.leliang.R;
import com.gensdai.leliang.base.BaseActivity;
import com.gensdai.leliang.common.adapter.RefundListAdapterRec;
import com.gensdai.leliang.common.bean.ApplyOrderInfoBean;
import com.gensdai.leliang.entity.parseBean.BaseParseList;
import com.gensdai.leliang.remoteInterface.RetrofitFactory;
import com.gensdai.leliang.retrofitUtils.BaseObserverList;
import com.gensdai.leliang.retrofitUtils.ModelFilteredFactory;
import com.gensdai.leliang.utils.PreferencesUtils;
import com.scwang.smartrefresh.layout.SmartRefreshLayout;
import com.scwang.smartrefresh.layout.api.DefaultRefreshFooterCreater;
import com.scwang.smartrefresh.layout.api.DefaultRefreshHeaderCreater;
import com.scwang.smartrefresh.layout.api.RefreshFooter;
import com.scwang.smartrefresh.layout.api.RefreshHeader;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.ClassicsHeader;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadmoreListener;
import com.trello.rxlifecycle2.android.ActivityEvent;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

/**
 * Created by zsxx on 2017/9/21.
 */

public class ActivityApplyList extends BaseActivity {
    @BindView(R.id.refundList)
    RecyclerView refundList;

    @BindView(R.id.refreshLayout)
    SmartRefreshLayout refreshLayout;


    int pageNum = 1;
    @BindView(R.id.empty_view)
    RelativeLayout emptyView;

    @Override
    protected String getTitleStr() {
        return "退款/售后";
    }

    @Override
    protected boolean isShowBackButton() {
        return true;
    }

    @Override
    protected boolean isCustomTitle() {
        return false;
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.activity_apply_list;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ButterKnife.bind(this);
        initRecyclerView(refundList);

        initrefreshlayout();
    }


    private void initrefreshlayout() {
        refreshLayout.setDefaultRefreshHeaderCreater(new DefaultRefreshHeaderCreater() {
            @Override
            public RefreshHeader createRefreshHeader(Context context, RefreshLayout layout) {
                //指定为经典Header，默认是 贝塞尔雷达Header
                return new ClassicsHeader(context).setSpinnerStyle(SpinnerStyle.Translate);
            }
        });

        refreshLayout.setDefaultRefreshFooterCreater(new DefaultRefreshFooterCreater() {
            @Override
            public RefreshFooter createRefreshFooter(Context context, RefreshLayout layout) {
                //指定为经典Footer，默认是 BallPulseFooter
                return new ClassicsFooter(context).setSpinnerStyle(SpinnerStyle.Translate);
            }
        });

        refreshLayout.setOnRefreshLoadmoreListener(new OnRefreshLoadmoreListener() {
            @Override
            public void onLoadmore(RefreshLayout refreshlayout) {
                getrefundList(true);
            }

            @Override
            public void onRefresh(RefreshLayout refreshlayout) {
                pageNum = 1;
                getrefundList(false);
            }
        });

        //设置滚动到最底部是否加载更多
        refreshLayout.setEnableAutoLoadmore(true);
        refreshLayout.setDisableContentWhenRefresh(true);
        refreshLayout.autoRefresh();
    }


    private void getrefundList(final boolean loadMore) {
        String userid = PreferencesUtils.getStringPreference(this, OrderPreperActivity.prefreceName, OrderPreperActivity.prefrece_userid, ""); //获取用户id没有登陆就是没有
        Map<String, String> params = new HashMap<>();
        params.put("userId", userid);
        params.put("page", pageNum + "");
        ModelFilteredFactory.compose(RetrofitFactory.getInstance().API().refundlist(params))
                .compose(this.<BaseParseList<ApplyOrderInfoBean>>bindUntilEvent(ActivityEvent.DESTROY)) //跟生命周期绑定一起
                .doOnSubscribe(new Consumer<Disposable>() {
                    @Override
                    public void accept(@NonNull Disposable disposable) throws Exception {
                        //开始监听前的处理，一般用于显示dialog什么的
                        Log.d("accept", "accept");
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new BaseObserverList<ApplyOrderInfoBean>(this) {

                    @Override
                    public void onRequestEnd() {
                        super.onRequestEnd();
                    }

                    @Override
                    public void onHandleSuccess(List<ApplyOrderInfoBean> t) {
                        attrRecycler(t, loadMore);
                    }


                    @Override
                    public void onHandleError(int code, String message) {

                    }
                });
    }


    LinearLayoutHelper layoutHelper;
    List<ApplyOrderInfoBean> beans;
    RefundListAdapterRec adapter;

    private void attrRecycler(List<ApplyOrderInfoBean> t, boolean isLoadMore) {

        if (t != null) {
            if (t.size() > 0) {
                refreshLayout.setEnableLoadmore(true);
                pageNum += 1;
            } else {
                refreshLayout.setEnableLoadmore(false);
            }
            if (layoutHelper == null) {
                layoutHelper = new LinearLayoutHelper();
                layoutHelper.setDividerHeight(60);
                layoutHelper.setBgColor(ContextCompat.getColor(this, R.color.bgColor_new));
            }

            if (isLoadMore) {
                beans.addAll(t);
                adapter.notifyDataSetChanged();
                delegateAdapter.notifyDataSetChanged();
                refreshLayout.finishLoadmore();
            } else {
                refreshLayout.finishRefresh();
                beans = new ArrayList<>();
                if (adapters != null) {
                    beans = t;
                    adapter = new RefundListAdapterRec(this, layoutHelper, beans);
                    adapter.setOnInfoItemClick(new RefundListAdapterRec.OnInfoItemClick() {
                        @Override
                        public void onClick(int position, String orderid) {
                            Intent it = new Intent(ActivityApplyList.this, ActivityApplyResultInfo.class);
                            it.putExtra(ActivityApplyResultInfo.EXTRA_ORDERID, orderid);
                            startActivity(it);
                        }
                    });
                    adapters.clear();
                    adapters.add(adapter);

                } else {
                    adapters = new LinkedList<>();
                    beans = t;
                    adapter = new RefundListAdapterRec(this, layoutHelper, beans);
                    adapter.setOnInfoItemClick(new RefundListAdapterRec.OnInfoItemClick() {
                        @Override
                        public void onClick(int position, String orderid) {
                            Intent it = new Intent(ActivityApplyList.this, ActivityApplyResultInfo.class);
                            it.putExtra(ActivityApplyResultInfo.EXTRA_ORDERID, orderid);
                            startActivity(it);
                        }
                    });
                    adapters.clear();
                    adapters.add(adapter);
                }

                //初始化完毕后开始适配
                delegateAdapter.setAdapters(adapters);
                delegateAdapter.notifyDataSetChanged();

                if(beans.size() > 0){
                    emptyView.setVisibility(View.GONE);
                }else{
                    emptyView.setVisibility(View.VISIBLE);
                }
            }
        }

    }


    DelegateAdapter delegateAdapter;
    List<DelegateAdapter.Adapter> adapters;

    private void initRecyclerView(RecyclerView recyclerView) {
        //创建线性布局
        final VirtualLayoutManager layoutManager = new VirtualLayoutManager(this);
        recyclerView.setLayoutManager(layoutManager);
        // layoutManager.setReverseLayout(true);

        RecyclerView.ItemDecoration itemDecoration = new RecyclerView.ItemDecoration() {
            public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
                int position = ((VirtualLayoutManager.LayoutParams) view.getLayoutParams()).getViewPosition();
                outRect.set(4, 4, 4, 4);
            }
        };

        final RecyclerView.RecycledViewPool viewPool = new RecyclerView.RecycledViewPool();

        recyclerView.setRecycledViewPool(viewPool);

        // recyclerView.addItemDecoration(itemDecoration);
        viewPool.setMaxRecycledViews(0, 20);

        delegateAdapter = new DelegateAdapter(layoutManager, false);

        recyclerView.setAdapter(delegateAdapter);

        adapters = new LinkedList<>();
    }
}
